package cn.iune.erp.inventory;

import java.math.BigDecimal;
import java.sql.SQLException;
import java.text.ParseException;
import java.util.ArrayList;
import java.util.HashMap;
import java.util.List;
import java.util.Map;

//import org.slf4j.Logger;
//import org.slf4j.LoggerFactory;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Service;
import org.springframework.transaction.annotation.Propagation;
import org.springframework.transaction.annotation.Transactional;

import com.alibaba.fastjson.JSON;
import com.alibaba.fastjson.JSONArray;
import com.alibaba.fastjson.JSONObject;
import com.justep.baas.Utils;
import com.justep.baas.data.Row;
import com.justep.baas.data.RowState;
import com.justep.baas.data.Table;
import com.justep.baas.data.Transform;




@Transactional
@Service
public class ItemBatchServiceImpl implements IItemBatchService {
	
//	private final Logger log = LoggerFactory.getLogger(StorageServiceImpl.class);

	@Autowired
	private IItemBatchDao dao;
	
	/* (non-Javadoc)
	 * @see com.iune.erp.inventory.IItemBatchService#getAll()
	 */
	@Override
	public List<ItemBatch> getAll(){
		return dao.getAll();
	}
	/* (non-Javadoc)
	 * @see com.iune.erp.inventory.IItemBatchService#getByID(java.lang.String)
	 */
	@Override
	public ItemBatch getByID(String fID) {
		return dao.getByID(fID);
	}

	/* (non-Javadoc)
	 * @see com.iune.erp.inventory.IItemBatchService#delete(java.lang.String)
	 */
	@Transactional
	@Override
	public void delete(String fID) {
		dao.delete(fID);
	}

	/* (non-Javadoc)
	 * @see com.iune.erp.inventory.IItemBatchService#getByNo(java.lang.String, java.lang.String, java.lang.String)
	 */
	@Override
	public ItemBatch getByNo(String itemID, String batchNo, String enterpriseNo) {
		return dao.getByNo(itemID, batchNo, enterpriseNo);
	}
	
	@Transactional

	/* (non-Javadoc)
	 * @see com.iune.erp.inventory.IItemBatchService#save(com.alibaba.fastjson.JSONObject)
	 */
	public JSONObject save(JSONObject object) throws ParseException  {
		// JSON转换Table
		Table table = Transform.jsonToTable(object);
		
		JSONObject data = new JSONObject();
		data.put("concept", table.getTableName());
		JSONArray rows = new JSONArray();
		List<String> idsNew = new ArrayList<String>();
		List<String> idsDel = new ArrayList<String>();
		
		List<Row> list = table.getRows();
		for(Row row : list){
			JSONObject javaObject= Transform.rowToJavaObject(table, row);
			ItemBatch obj = JSON.toJavaObject(javaObject, ItemBatch.class);
			if(RowState.NEW.equals(obj.getRowState())){
				dao.insert(obj);
				idsNew.add(obj.getfID());
			}
			if(RowState.DELETE.equals(obj.getRowState())){
				dao.delete(obj.getfID());
				idsDel.add(obj.getfID());
			}
			if(RowState.EDIT.equals(obj.getRowState())){
				ItemBatch objNew = dao.update(obj);
				//返回+1后的version到前台BizData中进行刷新，使得前台的version与后台的一致。
				///////////////////////////////////////////////////////////////////////
				JSONObject jsonRow = new JSONObject();
				jsonRow.put("id", obj.getfID());
				jsonRow.put("version", objNew.getVersion());
				rows.add(jsonRow);
				//////////////////////////////////////////////////////////////////////
			}
		}
		
		data.put("rows", rows);
		data.put("idsNew", idsNew);
		data.put("idsDel", idsDel);
		
		return data;
	}


	
	///////////////////////业务功能///////////////////////////////////////

	//入库登记
	/* (non-Javadoc)
	 * @see com.iune.erp.inventory.IItemBatchService#storeRegister(java.lang.String, java.lang.String, java.lang.String, java.math.BigDecimal, java.math.BigDecimal, java.sql.Date, java.sql.Date, java.sql.Date, java.lang.String, java.lang.String, java.lang.String, java.lang.String, java.lang.String, java.lang.String, java.lang.String, java.lang.String, java.lang.String, java.lang.String)
	 */
	@Transactional
	@Override
	public int storeRegister(
			String batchNo
			, String batchDescribe
			, String itemID
			, BigDecimal itemQuantity
			, BigDecimal pieceQuantity
			, String enterpriseNo
			, String enterpriseName
			) {
		
		ItemBatch itemBatch = dao.getByNo(itemID, batchNo, enterpriseNo);
		/*
		//首先判断是否存在记录，如果不存在就创建
		if (itemBatch==null) {
			
			String cUsercode = SecurityService.getCurrentPerson().getsCode();
			String cUsername = SecurityService.getCurrentPerson().getsName();
			String userId = SecurityService.getCurrentPerson().getsID();
//			String enterpriseNo = SecurityService.getCurrentOgn().getsFID();
//			String enterpriseName = SecurityService.getCurrentOgn().getsName();

			itemBatch = this.packing(cUsercode, cUsername, userId, enterpriseNo, enterpriseName);
			
			itemBatch.setItemID(itemID);
			itemBatch.setItemProperty(itemProperty);
			itemBatch.setBatchNo(batchNo);
			itemBatch.setBatchDescribe(batchDescribe);
			
			itemBatch.setFirstStoreDate(SystemService.getCurrentDate());
			itemBatch.setProduceDate(produceDate);
			itemBatch.setValidDate(validDate);
			itemBatch.setCheckoutAgainDate(checkoutAgainDate);
			
			itemBatch.setBrand(brand);
			itemBatch.setBrandLabel(brandLabel);
			itemBatch.setManufacturer(manufacturer);
			itemBatch.setPlaceOrigin(placeOrigin);
			itemBatch.setProviderID(providerID);
			
			itemBatch.setOrigin(origin);
			itemBatch.setOriginName(originName);
			itemBatch.setOriginNo(originNo);
			
			itemBatch.setLockFlag("Y");
			
			dao.update(itemBatch);
		}
		*/
		//登记
		//此处为已经存在批号档案，只登记数量
		itemBatch.setItemQuantityL(itemBatch.getItemQuantityL().add(itemQuantity));
		itemBatch.setPieceQuantityL(itemBatch.getPieceQuantityL().add(pieceQuantity));
		
		dao.update(itemBatch);
		//判断是否需要锁定，如果是创始人更新，则不需要锁定，否则锁定。（为了在锁定状态下不允许删除）
		/*
		if(workNo.equals(this.getWorkNo())){
			this.setLockFlag("N");
		}else{
			this.setLockFlag("Y");
		}
		*/
		
		return 0;
	}

	//出库登记
	/* (non-Javadoc)
	 * @see com.iune.erp.inventory.IItemBatchService#pickRegister(java.lang.String, java.lang.String, java.lang.String, java.math.BigDecimal, java.math.BigDecimal, java.sql.Date, java.sql.Date, java.sql.Date, java.lang.String, java.lang.String, java.lang.String, java.lang.String, java.lang.String, java.lang.String, java.lang.String, java.lang.String, java.lang.String, java.lang.String)
	 */
	@Transactional
	@Override
	public int pickRegister(
			String batchNo
			, String batchDescribe
			, String itemID
			, BigDecimal itemQuantity
			, BigDecimal pieceQuantity
			, String enterpriseNo
			, String enterpriseName
			) {
		
		ItemBatch itemBatch = dao.getByNo(itemID,batchNo, enterpriseNo);
		/*
		//首先判断是否存在记录，如果不存在就创建
		if (itemBatch==null) {
			
			String cUsercode = SecurityService.getCurrentPerson().getsCode();
			String cUsername = SecurityService.getCurrentPerson().getsName();
			String userId = SecurityService.getCurrentPerson().getsID();
//			String enterpriseNo = SecurityService.getCurrentOgn().getsFID();
//			String enterpriseName = SecurityService.getCurrentOgn().getsName();

			itemBatch = this.packing(cUsercode, cUsername, userId, enterpriseNo, enterpriseName);
			
			itemBatch.setItemID(itemID);
			itemBatch.setItemProperty(itemProperty);
			itemBatch.setBatchNo(batchNo);
			itemBatch.setBatchDescribe(batchDescribe);
			
			itemBatch.setFirstStoreDate(SystemService.getCurrentDate());
			itemBatch.setProduceDate(produceDate);
			itemBatch.setValidDate(validDate);
			itemBatch.setCheckoutAgainDate(checkoutAgainDate);
			
			itemBatch.setBrand(brand);
			itemBatch.setBrandLabel(brandLabel);
			itemBatch.setManufacturer(manufacturer);
			itemBatch.setPlaceOrigin(placeOrigin);
			itemBatch.setProviderID(providerID);
			
			itemBatch.setOrigin(origin);
			itemBatch.setOriginName(originName);
			itemBatch.setOriginNo(originNo);
			
			itemBatch.setLockFlag("Y");
			
			dao.update(itemBatch);
		}
		*/
		//登记
		//此处为已经存在批号档案，只登记数量
		itemBatch.setItemQuantityL(itemBatch.getItemQuantityL().subtract(itemQuantity));
		itemBatch.setPieceQuantityL(itemBatch.getPieceQuantityL().subtract(pieceQuantity));
		
		dao.update(itemBatch);
		
		//判断是否需要锁定，如果是创始人更新，则不需要锁定，否则锁定。（为了在锁定状态下不允许删除）
		/*
		if(workNo.equals(this.getWorkNo())){
			this.setLockFlag("N");
		}else{
			this.setLockFlag("Y");
		}
		*/

		return 0;
	}
	
	
	@Override
	public ItemBatch packing(
			String cUsercode//=com.justep.system.context.ContextHelper.getOperator().getCode();
			,String cUsername//=com.justep.system.context.ContextHelper.getOperator().getName();
			,String userId //= com.justep.system.context.ContextHelper.getOperator().getID();
			,String enterpriseNo //= this.getEnterpriseNo();
			,String enterpriseName //= this.getEnterpriseName();
			){
		ItemBatch obj = new ItemBatch();
		String fID = Utils.getUUID();
		obj.setfID(fID);
		
		obj.setState("active");
		obj.setStatus("open");
		obj.setSystemCode("IM");
		obj.setBillType("PHDA");
		obj.setBillTypeName("批号档案");
		obj.setOrderDate(Utils.getCurrentDate());
		
		
		obj.setComments("自动创建");
		
		obj.setcUsercode(cUsercode);
		obj.setcUsername(cUsername);
		obj.setcDatetime(Utils.getCurrentDateTime());
		obj.setUserId(userId);
		obj.setEnterpriseNo(enterpriseNo);
		obj.setEnterpriseName(enterpriseName);
		
		obj.setVersion(0);
		
		return obj;
	}
	
	
	
	/* (non-Javadoc)
	 * @see com.iune.erp.inventory.IItemBatchService#toMap(com.iune.erp.inventory.ItemBatch)
	 */
	@Override
	public Map<String,Object> toMap(ItemBatch obj){
		Map<String,Object> map =  new HashMap<String, Object>();
		//可读取标志
		map.put("state", "success");
		
		map.put("fID", obj.getfID());
		map.put("itemID", obj.getItemID());
//		map.put("itemDescribe", obj.getItemDescribe());
//		map.put("rationSize", obj.getRationSize());
//		map.put("unitCode", obj.getUnitCode());
//		map.put("unitName", obj.getUnitName());
		map.put("batchNo", obj.getBatchNo());
		map.put("batchDescribe", obj.getBatchDescribe());
		
		map.put("firstStoreDate", obj.getFirstStoreDate());
		map.put("produceDate", obj.getProduceDate());
		map.put("validDate", obj.getValidDate());
		map.put("checkoutAgainDate", obj.getCheckoutAgainDate());
		map.put("lastCheckDate", obj.getLastCheckDate());
		
		map.put("brand", obj.getBrand());
		map.put("brandLabel", obj.getBrandLabel());
		map.put("placeOrigin", obj.getPlaceOrigin());
		map.put("manufacturer", obj.getManufacturer());
//		map.put("providerNo", obj.getProviderNo());
//		map.put("shortName", obj.getShortName());
//		map.put("providerName", obj.getProviderName());
		
		map.put("origin", obj.getOrigin());
		map.put("originName", obj.getOriginName());
		map.put("originNo", obj.getOriginNo());
		
//		map.put("colorCode", obj.getColorCode());
//		map.put("colorLabel", obj.getColorLabel());
//		map.put("sizeCode", obj.getSizeCode());
//		map.put("sizeLabel", obj.getSizeLabel());

		return map;
	}

	
	@Override
	public JSONObject newData(JSONObject data) {
		return dao.create(data);
	}
	
	@Override
	public JSONObject deleteData(JSONObject param) {
		//System.out.println("fileFactoryCreate.param-->>"+param.toJSONString());
		JSONArray ids = param.getJSONArray("ids");
		for(int i=0;i<ids.size();i++){
			String id = ids.getString(i);
			//这里可以增加是否可删除的判断
			
			dao.delete(id);
		}

		JSONObject data = new JSONObject();
		data.put("ids", ids);
		
		JSONObject json = new JSONObject();
		json.put("code", 0);
		json.put("msg", "success");
		json.put("data", data);
		
		return json;
	}

	/*
	在@Transaction注解中定义noRollbackFor和RollbackFor指定某种异常是否回滚。 
	@Transactional(noRollbackFor=RuntimeException.class) 
	@Transactional(RollbackFor=Exception.class) 
	*/
	@Transactional
	@Override
	public JSONObject saveData(JSONObject param) {
		//Spring的事务管理默认只对出现运行期异常(java.lang.RuntimeException及其子类)进行回滚。 
		//如果一个方法抛出Exception或者Checked异常，Spring事务管理默认不进行回滚。 
		// JSON转换Table
		//System.out.println(object);
		JSONObject data;
		try {
			data = this.save(param);
					
			JSONObject json = new JSONObject();
			json.put("code", 0);
			json.put("msg", "success");
			json.put("data", data);
			
			return json;
			
		} catch (ParseException e) {
			// TODO Auto-generated catch block
			e.printStackTrace();
			
			JSONObject json = new JSONObject();
			json.put("code", -1);
			json.put("msg", e.getMessage());
			
			return json;
		} 
	}
	
	/* (non-Javadoc)
	 * @see com.iune.erp.baseinfo.aaa#queryJDBC(com.alibaba.fastjson.JSONObject)
	 */
	@Transactional(propagation=Propagation.NOT_SUPPORTED,readOnly=true)
	@Override
	public JSONObject queryData(JSONObject param){
		//在此层面（ServiceImpl）统一处理异常，此层面直接被controller调用，面对BizData
		
		try {
			JSONObject jsonTable = dao.query(param);
			
			JSONObject json = new JSONObject();
			json.put("code", 0);
			json.put("msg", "success");
			json.put("data", jsonTable);
			
			return json;
		} catch (SQLException e) {
			e.printStackTrace();
			
			JSONObject json = new JSONObject();
			json.put("code", -1);
			json.put("msg", e.getMessage());
			return json;
		}
	}

	@Override
	public JSONObject validData(JSONObject param) {
		// TODO Auto-generated method stub
		return null;
	}

}
